import type {AxiosResponse, AxiosRequestConfig, AxiosError} from 'axios'
import axios from 'axios'
import {showNotify, showToast} from 'vant'

const instance = axios.create({
  baseURL: 'https://geek.itheima.net/v1_0'
})

instance.interceptors.request.use(
  (config) => {
    try {
      // mk.queryUser() 目前会有警告
      const token = jky.queryToken().token
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
    } catch (e) {
      showToast({message: '美蔻SDK异常' + e})
    }
    return config
  },
  (err) => {
    Promise.reject(err)
  }
)
instance.interceptors.response.use((response: AxiosResponse) => {
  if (response.status === 200 || 201 || 204) {
    return response
  }
  showNotify({type: 'warning', message:response.data.message, position: 'bottom'});
  return Promise.reject(new Error(response.data.message))
}, (error: AxiosError) => {
  if (error.status === 401) {
    jky.gotoLogin()
    return
  }
  return Promise.reject(error)
})

function axiosRequest<T = null, D = null>(config: AxiosRequestConfig<D>) {
  return instance<null, AxiosResponse<IRes<T>, null>, D>(config)
}

export {axiosRequest}
